/**
 * Created by lishiming on 14-3-14.
 */
var url = require("url");
var querystring = require("querystring");
var crypto = require('crypto');
var path = require('path');
var fs = require('fs');

function getAssistantValue(request) {
    var arg = url.parse(request.url).query;
    var assistant = querystring.parse(arg).a;
    return assistant;
}

exports.getToken = function (request) {
    var arg = url.parse(request.url).query;
    var assistant = querystring.parse(arg).token;
    return assistant;
}

exports.getPhone = function (request) {
    var arg = url.parse(request.url).query;
    var assistant = querystring.parse(arg).phone;
    return assistant;
}

exports.getPW = function (request) {
    var arg = url.parse(request.url).query;
    var assistant = querystring.parse(arg).pw;
    return assistant;
}

function getMainValue(request) {
    var arg = url.parse(request.url).query;
    var main = querystring.parse(arg).m;
    return main;
}

exports.getFirstValue = function (strurl) {
    var strarr = strurl.split('/');
    if (strarr.length >= 2) {
        return strarr[1];
    } else {
        return '';
    }
};

exports.getSecondValue = function (strurl) {
    var strarr = strurl.split('/');
    if (strarr.length >= 3) {
        var secondvar = strarr[2];
        var seartch = secondvar.indexOf('?');
        if (seartch != -1) {
            return secondvar.substring(0, seartch);
        } else {
            return strarr[2];
        }
    } else {
        return '';
    }
};

function getDeviceID(request) {
    var arg = url.parse(request.url).query;
    var assistant = querystring.parse(arg).device_id;
    return assistant;
}

function getRegistID(request) {
    var arg = url.parse(request.url).query;
    var assistant = querystring.parse(arg).user_id;
    return assistant;
}

function getLimit(request) {
    var arg = url.parse(request.url).query;
    var assistant = querystring.parse(arg).count;
    return assistant;
}

function getPage(request) {
    var arg = url.parse(request.url).query;
    var assistant = querystring.parse(arg).page;
    return assistant;
}

function getpid(request) {
    var arg = url.parse(request.url).query;
    var assistant = querystring.parse(arg).product_id;
    return assistant;
}

/**
 * 判断post参数
 * @param response
 * @param errstr
 * @return json化后的参数
 */
exports.checkoutdata = function (res, requestData) {
    var phone = null;
    if (requestData.length > 0) {
        try {
            var phone = JSON.parse(requestData);
        }
        catch (err) {
            returnErr(res, '参数错误', 5);
            return null;
        }
    } else {
        returnErr(res, '无数据', 5);
        return null;
    }

    return phone;
}

exports.getSelfPlatform = function (request) {
    var arg = url.parse(request.url).query;
    var assistant = querystring.parse(arg).platform;
    return assistant;
}

exports.getSelfVersionCount = function (request) {
    var arg = url.parse(request.url).query;
    var assistant = querystring.parse(arg).vc;
    return assistant;
}

/**
 * 返回 错误数据
 * @param response
 * @param errstr
 */
function returnErr(response, errstr, code) {
    var responsevalue = {
        data: {},
        code: code,
        error_msg: errstr
    }

    if (code == 5) {
        responsevalue.error_msg = '传入参数错误';
    }

    var postData = JSON.stringify(responsevalue);
    response.writeHead(200, {
        "Content-Type": "text/html;charset=UTF-8",
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
        'access-control-allow-methods': 'GET, POST, DELETE, PUT, PATCH, OPTIONS'
    });
    var contentType = response.getHeader('Access-Control-Allow-Origin');
    response.write(postData);
    response.end();

    console.log(errstr);
}

/**
 * 带有相应状态的错误返回
 * @param response
 * @param errstr
 * @param statestr
 */
function returnErrWithResponseState(response, errstr, statestr) {
    var responsevalue = {
        info: {
            extra: '',
            data: ''
        },
        response_status: statestr,
        result: 0,
        msg: errstr
    };
    var postData = JSON.stringify(responsevalue);
    response.writeHead(200, { "Content-Type": "text/html;charset=UTF-8" });
    response.write(postData);
    response.end();
}

/**
 * 返回正确数据
 * @param response
 * @param responsevalue
 * @param msg
 */
function returnValue(response, responsevalue, msg) {
    responsevalue.code = 0;
    responsevalue.error_msg = msg;
    var postData = JSON.stringify(responsevalue);
    response.writeHead(200, {
        "Content-Type": "text/html;charset=UTF-8",
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'
    });
    response.write(postData);
    response.end();

    console.log(msg);
}


/**
 * ejs框架 封装 页面数据展示
 * @param response
 * @param data    数据
 * @param action  页面
 */
function render(response, data, action) {
    var ejs = require('ejs');
    var action = action ? action : 'index',
        // type        = "success" ? "success" : "error";
        filename = path.join(process.cwd(), '/views/' + action + '.ejs'),
        str = fs.readFileSync(filename, 'utf8'),
        ret = ejs.render(str, {
            // type: type,
            data: data,
            filename: filename
        });
    // console.log(data);
    response.writeHead(200, { "Content-Type": "text/html" });
    response.write(ret);
    response.end();
};



exports.success = function (response, data, action) {
    var actions = action === 'success' ? "success" : "";
    render(response, data, actions);
}

exports.render = render;

exports.location = function (response, url) {
    response.setHeader('Location', url);
    response.end();
};

exports.redirect = function (response, url) {
    response.writeHead(302, { 'Location': url });
    response.end();
};

/**
 * token 过期
 * @param response
 */
exports.returnTokenerr = function (response) {
    responsevalue = {};
    responsevalue.response_status = 'false';
    responsevalue.result = 2;
    responsevalue.msg = 'token过期，请重新登陆';
    var postData = JSON.stringify(responsevalue);
    response.writeHead(200, {
        "Content-Type": "text/html;charset=UTF-8",
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'
    });
    response.write(postData);
    response.end();
}

/**
 * md5 加密
 * @param str
 * @param encoding
 * @constructor
 */
function MD5(str, encoding) {
    return crypto.createHash('md5').update(str).digest(encoding || 'hex');
}

exports.getVersion = function (request) {
    var arg = url.parse(request.url).query;
    var assistant = querystring.parse(arg).vn;
    return assistant;
}

exports.getChannel = function (request) {
    var arg = url.parse(request.url).query;
    var assistant = querystring.parse(arg).channel;
    return assistant;
}

exports.guid = function guid() {
    return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
};

exports.putoutIP = function (request) {
    var ip;
    if (request.headers['x-forwarded-for']) {
        ip = request.headers['x-forwarded-for'].split(",")[0];
    } else if (request.connection && request.connection.remoteAddress) {
        ip = request.connection.remoteAddress;
    } else {
        ip = request.ip;
    }
    var now = new Date();
    // console.log(ip + '   ' + now.toLocaleString());
}

exports.getValueByDoc = function (doc) {
    return {
        user_id: doc._id,
        token: doc.token
        , nickname: doc.nickname
        , sex: doc.sex
        , sexual: doc.sexual
        , phone: doc.phone
        , isbindqq: doc.isbindqq
        , isbindweixin: doc.isbindweixin
        , isbindweibo: doc.isbindweibo
        , qquid: doc.qquid
        , weixinuid: doc.weixinuid
        , weibouid: doc.weibouid
        , headurl: doc.headurl
        , nsnumber: doc.nsnumber
    }
}

exports.checkoutPhone = function (phone, response) {
    var isphone = true;
    if (phone) {
        var reg = /^\d{11}$/;
        if (!reg.test(phone)) {
            this.returnErr(response, '手机号需为11位数字');
            isphone = false;
        }
    } else {
        this.returnErr(response, '无手机号参数');
        isphone = false;
    }
    return isphone;
};

exports.isArrayFn = function (value) {
    if (typeof Array.isArray === "function") {
        return Array.isArray(value);
    } else {
        return Object.prototype.toString.call(value) === "[object Array]";
    }
}

/**
 * 输出log
 * @param req request请求
 * @param requestData body json数据
 * @returns {number}
 */
exports.putlog = function (req, requestData) {
    var d = new Date()
    console.log(d.toString())
    console.log(req.url);
    console.log(requestData);
}

//生成随机id(纯数字)
exports.getRandomStr = function (len) {
    var text = "";
    var possible = "0123456789";
    for (var i = 0; i < len; i++)
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    return text;
}

exports.defaultValue = {
    info: {
        extra: null,
        data: {
        }
    }
}

exports.getMainValue = getMainValue;
exports.getAssistantValue = getAssistantValue;
exports.returnErr = returnErr;
exports.returnValue = returnValue;
exports.returnErrWithResponseState = returnErrWithResponseState;
exports.MD5 = MD5;
exports.getDeviceID = getDeviceID;
exports.getRegistID = getRegistID;
exports.getLimit = getLimit;
exports.getPage = getPage;
exports.getpid = getpid;

exports.releaseip = 'www.toupai360.com';
exports.testip = 'latest.toupai360.com';
exports.localip = '127.0.0.1';

